#!/usr/bin/python
#-*-coding:utf-8-*-

import os,sys
from os.path import isfile
from os import popen,kill,_exit
import threading
import time,datetime,calendar

class manager:
    def __init__(self):
        self.name = None
        self.thread = None
        self.config = {
            'diftime':3,
            'diftype':'seconds',
            'rundirs':None,
            'runnums':3,
            'putargs':None,
            'printres':'no',
            'printcmd':'no'
        }

    def enableTask(self,name = None,param=None , threadName = None , pid = None):
        self.config.update(param)
        self.name = name
        self.thread = threadName
        self.pid    = pid
        self.log('正在执行应用脚本:%s,间隔 %d %s,启用%d个线程... ' % (self.name,self.config['diftime'],self.config['diftype'],self.config['runnums']))

        if self.config.has_key('command') is False:
            self.log('应用:%s,config param -> command is must!' % self.name)
            return False

        if self.config.has_key('runfile') is False or self.config['runfile'] is None:
            self.log('应用:%s,config param -> runfile is must!' % self.name)
            return False

        if isfile(self.config['rundirs'] + self.config['runfile']) is False:
            self.log('应用:%s,runfile is not found!' % self.name)
            return False

        if self.config['diftype'] == 'minute':
            sleep = self.config['diftime'] * 60
        elif self.config['diftype'] == 'hour':
            sleep = self.config['diftime'] * 3600
        elif self.config['diftype'] == 'day':
            sleep = self.config['diftime'] * 86400
        elif self.config['diftype'] == 'month':
            now_date = datetime.datetime.now()
            now_month= calendar.monthrange(now_date.year,now_date.month)[1]
            sleep = self.config['diftime'] * (86400*now_month)
        else:
            sleep = self.config['diftime']

        while True:
            #创建线程池
            threads = []
            for i in xrange(self.config['runnums']):
                t = threading.Thread(target=self.execFunc)
                t.start()
                threads.append(t)
            for t in threads:
                t.join()
            time.sleep(sleep)

    def execFunc(self):
        self.log('应用:%s,共计线程:%d,当前线程名称:%s...' % (self.name,self.config['runnums'],threading.currentThread().getName()))

        if self.config.has_key('putargs') is False or self.config['putargs'] is None:
            execArgs = ''
        else:
            execArgs = ' '.join(self.config['putargs'])

        return self.script(self.config['command'],self.config['rundirs'] + self.config['runfile'],execArgs)

    def script(self,command = None,file = None, args = None):
        exec_command = '%s %s %s' % (command,file,args)
        if self.config['printcmd'] == 'yes':
            print exec_command
        res = popen(exec_command)
        if self.config['printres'] == 'yes':
            print res.read()
        return

    def log(self,msg = None , isEnd = False):
        print '%s # [PID:%d] >>> %s' % (self.thread,self.pid,msg)
        if isEnd is True:
            sys.exit(0)
            os.exit(0)


